import { createStore } from 'vuex'
import persisted from 'vuex-persistedstate'
export default createStore({
  state: {
    userInfo: {},
    products: []
  },
  getters: {
    goodNum(state) {
      let num = 0
      state.products.forEach(el => {
          num += el.num
      });
      return num
    },

    // 计算选中的商品总价
    // sum(state) {
    //   console.log(1);
    //   let price = 0
    //   state.products.forEach(item => {
    //     if(item.check) {
    //       price += item.num*item.price
    //     }
    //   })
    //   return price
    // }
  },
  mutations: {
    saveUserInfo(state, val) {
      state.userInfo = val
    },


    // 将商品添加进入购物车的逻辑
    productsAdd(state, obj) {
      let flag = true
      if(state.products.length === 0) {
        state.products.push(obj)
      } else {
        state.products.forEach(item => {
          if(item.upId === obj.upId && item.btmId === obj.btmId) {
            item.num += obj.num
            flag = false
          } 
        })
        if(flag) {
          state.products.push(obj)
        }
      }
      
    },


    // 删除商品的方法
    del(state, i) {
      state.products.splice(i, 1)
    },

    exitProducts(state, arr) {
      state.products = arr
    },

    check(state, i) {
      state.products[i].check = !state.products[i].check
    }
  },
  actions: {
  },
  modules: {
  },

  plugins: [
    persisted({
      reducer(state) {
        return {
          userInfo: state.userInfo,
          products: state.products
        }
      }
    })
  ]
})
